//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#include <buola/io/cfd.h>
#include <buola/io.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cerrno>

namespace buola { namespace io {

CFD::CFD(NOpenShm,const std::string &pName,EMode pMode,EPermission pPerm,bool *pCreated)
    :   mFD(-1)
{
    static const EMode lValidModes=EMode::OPENORCREATE|EMode::READWRITE|EMode::TRUNCATE;
    
    if((pMode|lValidModes)!=lValidModes)
        throw XArgument("invalid mode opening shared memory segment");
    
    int lFlags=0;

    switch((EMode)(pMode&EMode::READWRITE))
    {
        case EMode::READ:
        lFlags|=O_RDONLY;
        break;
        case EMode::READWRITE:
        lFlags|=O_RDWR;
        break;
    default:
        throw XArgument("invalid mode opening shared memory segment");
    }

    if((pMode&EMode::TRUNCATE)==EMode::TRUNCATE)
        lFlags|=O_TRUNC;

    std::string lName=(pName[0]=='/')?pName:'/'+pName;

    if((pMode&EMode::OPENORCREATE)==EMode::OPEN)
    {
        mFD=shm_open(pName.c_str(),lFlags,(mode_t)pPerm);
        if(pCreated) *pCreated=false;
    }
    else if((pMode&EMode::OPENORCREATE)==EMode::CREATE)
    {
        mFD=shm_open(pName.c_str(),lFlags|O_CREAT|O_EXCL,(mode_t)pPerm);
        if(pCreated) *pCreated=true;
    }
    else
    {
        if(pCreated)
        {
            //this is the messy case :)
            ///\todo There is a possible race condition if the file exists, but it is a symbolic link pointing
            ///nowhere. In this case, the first one will return EEXIST and the second one will return ENOENT,
            ///so we'll have an infinite loop. I'm not sure that this can happen with shared memory segments
            //it is a loop so that it doesn't fail when the file is destroyed after trying to create
            while(true)
            {
                //try creating
                if((mFD=shm_open(pName.c_str(),lFlags|O_CREAT|O_EXCL,(mode_t)pPerm))>=0||errno!=EEXIST)
                {
                    *pCreated=true;
                    break;
                }
                //try opening
                if((mFD=shm_open(pName.c_str(),lFlags,(mode_t)pPerm))>=0||errno!=ENOENT)
                {
                    *pCreated=false;
                    break;
                }
            }
        }
        else
        {
            mFD=shm_open(pName.c_str(),lFlags|O_CREAT,(mode_t)pPerm);
        }
    }

    if(mFD<0)
    {
        switch(errno)
        {
        case EEXIST:
            throw XAlready(I18N("File already exists creating shared memory"));
        case EACCES:
            throw XPermission(I18N("Permission problem opening shared memory"));
        case ENAMETOOLONG:
        case EINVAL:
            throw XArgument(I18N("Wrong name opening shared memory"));
        case ENOENT:
            throw XNotFound(pName+I18N(": File not found opening shared memory"));
        case EFAULT:
            throw XMemory(I18N("Segmentation fault opening shared memory"));
        case ENOMEM:
            throw XMemory(I18N("Out of memory opening shared memory"));
        case ENFILE:
        case EMFILE:
            throw XFull(I18N("Too many files opening shared memory"));
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal(I18N("Unexpected error opening shared memory"));
        }
    }
}
    
void CFD::Close()
{
    if(mFD==-1) return;
    
    if(close(mFD)!=0)
    {
        switch(errno)
        {
        case EBADF:
            throw XInvalid("closing invalid file descriptor");
        case EINTR:
            throw XIO("signal received closing file descriptor");
        case EIO:
            throw XIO("I/O error closing file descriptor");
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal("unexpected error closing file descriptor");
        }
    }
    
    mFD=-1;
}

void CFD::Truncate(std::size_t pLength)
{
    if(ftruncate(mFD,pLength)!=0)
    {
        switch(errno)
        {
        case EBADF:
        case EINVAL:
            throw XInvalid("truncating invalid file descriptor");
        case EFBIG:
            throw XArgument("invalid size truncating file descriptor");
        case EPERM:
        case ETXTBSY:
            throw XPermission(I18N("Permission problem truncating file descriptor"));
        case EIO:
            throw XIO("I/O error truncating file descriptor");
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal("unexpected error closing file descriptor");
        }
    }
}

std::size_t CFD::GetSize()
{
    struct stat lStat;

    if(fstat(mFD,&lStat)!=0)
    {
        switch(errno)
        {
        case EBADF:
            throw XInvalid("statting invalid file descriptor");
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal("unexpected error closing file descriptor");
        }
    }

    return lStat.st_size;
}

void *CFD::Map(EMode pMode,off_t pOffset,std::size_t pSize,void *pHint)
{
    static const EMode lValidModes=EMode::READWRITE|EMode::PRIVATE|EMode::EXEC|EMode::FIXEDADDRESS;

    if((pMode|lValidModes)!=lValidModes)
        throw XArgument("invalid mode mapping file descriptor");

    int lProt;
    int lFlags;
    
    switch((EMode)(pMode&EMode::READWRITE))
    {
    case EMode::READ:
        lProt=PROT_READ;
        lFlags=MAP_SHARED;
        break;
    case EMode::READWRITE:
        lProt=PROT_READ|PROT_WRITE;
        if((pMode&EMode::PRIVATE)==EMode::PRIVATE)
            lFlags=MAP_PRIVATE;
        else
            lFlags=MAP_SHARED;
        break;
    default:
        throw XArgument("invalid mode opening shared memory segment");
    }
    
    if(pMode&EMode::EXEC)
        lProt|=PROT_EXEC;
    
    if(pMode&EMode::FIXEDADDRESS)
        lFlags|=MAP_FIXED;
    
    void *lAddress=mmap(pHint,pSize,lProt,lFlags,mFD,pOffset);
    
    if(lAddress==MAP_FAILED)
    {
        switch(errno)
        {
        case EACCES:
        case EAGAIN:
        case EPERM:
        case ETXTBSY:
            throw XPermission(I18N("Permission problem mapping file descriptor"));
        case EBADF:
        case ENODEV:
            throw XInvalid(I18N("Mapping invalid file descriptor"));
        case EINVAL:
            throw XArgument(I18N("Wrong parameter mapping file descriptor"));
        case ENOMEM:
            throw XMemory(I18N("Out of memory mapping file descriptor"));
        case ENFILE:
            throw XFull(I18N("Too many files mapping file descriptor"));
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal(I18N("Unexpected error mapping file descriptor"));
        }
    }
    
    return lAddress;
}

void CFD::Unmap(void *pAddress,std::size_t pSize)
{
    if(munmap(pAddress,pSize)!=0)
    {
        switch(errno)
        {
        case EINVAL:
            throw XArgument(I18N("Wrong parameter unmapping file descriptor"));
        default:
            msg_warn() << FILE_AND_LINE "unexpected error " << errno << "\n";
            throw XInternal(I18N("Unexpected error unmapping file descriptor"));
        }
    }
}

size_t CFD::GetPageSize()
{
    size_t lPageSize=sysconf(_SC_PAGESIZE);
    return lPageSize;
}

/*namespace buola*/ } /*namespace buola*/ }
